package filesystem;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;

import javax.swing.filechooser.FileSystemView;

class FileNode extends LazyMutableTreeNode implements Comparable {
	private static FileNode[] EMPTY_ARRAY = new FileNode[0];
	private static FileSystemView fsv = FileSystemView.getFileSystemView();

	public FileNode(File file) {
		super(file);
	}

	public boolean canEnqueue() {
		return false == hasLoaded() && false == fsv.isFloppyDrive(getFile()) && false == fsv.isFileSystemRoot(getFile());
	}

	public boolean isLeaf() {
		if (!hasLoaded()) {
			return false;
		} else {
			return super.isLeaf();
		}
	}

	protected void loadChildren()
	{
		FileNode[] nodes = getChildren();
		for( FileNode node : nodes )
			this.add( node );
	}

	private FileNode[] getChildren()
	{
		File[] files = fsv.getFiles( getFile(), false );
		if( null == files || 0 == files.length )
			return EMPTY_ARRAY;
		//===============================
		ArrayList<FileNode> nodes = new ArrayList<FileNode>();
		// keep only directories, no "file" in the tree.
		for( File file : files )
			if( true == file.isDirectory() )
				nodes.add( new FileNode ( file ) );
		// sort directories, FileTreeNode implements Comparable
		FileNode[] result = nodes.toArray( EMPTY_ARRAY );
		Arrays.sort( result );
		return result;
	}

	public File getFile() {
		return (File) getUserObject();
	}

	public String toString() {
		return fsv.getSystemDisplayName(this.getFile());
	}

	public int compareTo(Object o) {
		if (false == o instanceof FileNode)
			return 1;
		return getFile().compareTo(((FileNode) o).getFile());
	}

	public void clear() {
		super.clear();
		// ((DefaultTreeModel)
		// this.chooserUI.tree.getModel()).nodeStructureChanged( this );
	}
}
